package com.example.baseapp.service.impl;

import com.example.baseapp.entity.OrderInfo;
import com.example.baseapp.entity.OrderDetail;
import com.example.baseapp.entity.Dish;
import com.example.baseapp.dto.OrderDetailDTO;
import com.example.baseapp.repository.OrderInfoRepository;
import com.example.baseapp.repository.OrderDetailRepository;
import com.example.baseapp.repository.DishRepository;
import com.example.baseapp.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {
    
    private static final Logger logger = LoggerFactory.getLogger(OrderServiceImpl.class);
    
    @Autowired
    private OrderInfoRepository orderInfoRepository;
    
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    
    @Autowired
    private DishRepository dishRepository;
    
    @Override
    @Transactional
    public OrderInfo createOrder(Long userId, String userName, String userPhone, String userAddress, String userDepartment, List<Map<String, Object>> items, String remark) {
        // 生成订单号
        String orderNo = generateOrderNo();
        
        // 计算总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (Map<String, Object> item : items) {
            Long dishId = Long.valueOf(item.get("dishId").toString());
            Integer quantity = Integer.valueOf(item.get("quantity").toString());
            BigDecimal price = new BigDecimal(item.get("price").toString());
            totalAmount = totalAmount.add(price.multiply(new BigDecimal(quantity)));
        }
        
        // 创建订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderNo);
        orderInfo.setUserId(userId);
        orderInfo.setUserName(userName);
        orderInfo.setUserPhone(userPhone);
        orderInfo.setUserAddress(userAddress);
        orderInfo.setUserDepartment(userDepartment);
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setStatus("PENDING");
        orderInfo.setRemark(remark);
        orderInfo.setCreateTime(LocalDateTime.now());
        orderInfo.setUpdateTime(LocalDateTime.now());
        orderInfo.setMealType("堂食");
        orderInfo.setMenuDate(java.time.LocalDate.now());
        orderInfo.setOrderDate(LocalDateTime.now());
        
        orderInfo = orderInfoRepository.save(orderInfo);
        
        // 创建订单明细
        for (Map<String, Object> item : items) {
            Long dishId = Long.valueOf(item.get("dishId").toString());
            Integer quantity = Integer.valueOf(item.get("quantity").toString());
            BigDecimal price = new BigDecimal(item.get("price").toString());
            
            // 从数据库获取菜品信息
            String dishName = "未知菜品";
            String dishDescription = "";
            String dishImage = "https://img.yzcdn.cn/vant/cat.jpeg";
            
            try {
                Optional<Dish> dish = dishRepository.findById(dishId);
                if (dish.isPresent()) {
                    Dish dishEntity = dish.get();
                    dishName = dishEntity.getName();
                    dishDescription = dishEntity.getDescription() != null ? dishEntity.getDescription() : "";
                    dishImage = dishEntity.getImage() != null ? dishEntity.getImage() : "https://img.yzcdn.cn/vant/cat.jpeg";
                }
            } catch (Exception e) {
                // 如果获取菜品信息失败，使用默认值
                dishName = "菜品" + dishId;
            }
            
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderInfo.getId());
            orderDetail.setDishId(dishId);
            orderDetail.setDishName(dishName);
            orderDetail.setDishDescription(dishDescription);
            orderDetail.setDishImage(dishImage);
            orderDetail.setPrice(price);
            orderDetail.setQuantity(quantity);
            orderDetail.setSubtotal(price.multiply(new BigDecimal(quantity)));
            orderDetail.setCreateTime(LocalDateTime.now());
            
            orderDetailRepository.save(orderDetail);
        }
        
        return orderInfo;
    }
    
    @Override
    @Transactional
    public OrderInfo payOrder(String orderNo, String paymentMethod) {
        OrderInfo order = orderInfoRepository.findByOrderNo(orderNo);
        if (order != null && "PENDING".equals(order.getStatus())) {
            order.setStatus("PAID");
            order.setPaymentMethod(paymentMethod);
            order.setPaymentTime(LocalDateTime.now());
            order.setUpdateTime(LocalDateTime.now());
            return orderInfoRepository.save(order);
        }
        return null;
    }
    
    @Override
    @Transactional
    public OrderInfo cancelOrder(String orderNo) {
        OrderInfo order = orderInfoRepository.findByOrderNo(orderNo);
        if (order != null && "PENDING".equals(order.getStatus())) {
            order.setStatus("CANCELLED");
            order.setUpdateTime(LocalDateTime.now());
            return orderInfoRepository.save(order);
        }
        return null;
    }
    
    @Override
    public List<OrderInfo> getUserOrders(Long userId) {
        return orderInfoRepository.findByUserIdOrderByCreateTimeDesc(userId);
    }
    
    @Override
    public OrderDetailDTO getOrderDetail(String orderNo) {
        logger.info("开始获取订单详情，订单号: {}", orderNo);
        
        if (orderNo == null || orderNo.trim().isEmpty()) {
            logger.warn("订单号为空");
            return null;
        }
        
        try {
            OrderInfo orderInfo = getOrderByOrderNo(orderNo);
            if (orderInfo != null) {
                logger.info("找到订单信息，订单ID: {}", orderInfo.getId());
                List<OrderDetail> orderDetails = getOrderDetails(orderInfo.getId());
                logger.info("找到订单明细数量: {}", orderDetails != null ? orderDetails.size() : 0);
                
                OrderDetailDTO orderDetailDTO = new OrderDetailDTO(orderInfo, orderDetails);
                logger.info("订单详情DTO创建成功");
                return orderDetailDTO;
            } else {
                logger.warn("未找到订单信息，订单号: {}", orderNo);
                return null;
            }
        } catch (Exception e) {
            logger.error("获取订单详情时发生异常", e);
            return null;
        }
    }
    
    @Override
    public OrderInfo getOrderByOrderNo(String orderNo) {
        return orderInfoRepository.findByOrderNo(orderNo);
    }
    
    @Override
    public OrderDetailDTO getOrderDetailById(Long orderId) {
        logger.info("开始根据ID获取订单详情，订单ID: {}", orderId);
        
        if (orderId == null) {
            logger.warn("订单ID为空");
            return null;
        }
        
        try {
            OrderInfo orderInfo = getOrderById(orderId);
            if (orderInfo != null) {
                logger.info("找到订单信息，订单ID: {}", orderInfo.getId());
                List<OrderDetail> orderDetails = getOrderDetails(orderInfo.getId());
                logger.info("找到订单明细数量: {}", orderDetails != null ? orderDetails.size() : 0);
                
                OrderDetailDTO orderDetailDTO = new OrderDetailDTO(orderInfo, orderDetails);
                logger.info("订单详情DTO创建成功");
                return orderDetailDTO;
            } else {
                logger.warn("未找到订单信息，订单ID: {}", orderId);
                return null;
            }
        } catch (Exception e) {
            logger.error("根据ID获取订单详情时发生异常", e);
            return null;
        }
    }
    
    @Override
    public OrderInfo getOrderById(Long orderId) {
        return orderInfoRepository.findById(orderId).orElse(null);
    }
    
    @Override
    public List<OrderDetail> getOrderDetails(Long orderId) {
        return orderDetailRepository.findByOrderIdOrderByCreateTimeAsc(orderId);
    }
    
    @Override
    @Transactional
    public OrderInfo updateOrderStatus(String orderNo, String newStatus) {
        logger.info("更新订单状态，订单号: {}, 新状态: {}", orderNo, newStatus);
        
        OrderInfo order = orderInfoRepository.findByOrderNo(orderNo);
        if (order == null) {
            logger.warn("订单不存在，订单号: {}", orderNo);
            return null;
        }
        
        // 更新订单状态
        order.setStatus(newStatus);
        order.setUpdateTime(LocalDateTime.now());
        
        // 如果状态是已支付，设置支付时间
        if ("PAID".equals(newStatus) && order.getPaymentTime() == null) {
            order.setPaymentTime(LocalDateTime.now());
        }
        
        OrderInfo updatedOrder = orderInfoRepository.save(order);
        logger.info("订单状态更新成功，订单号: {}, 新状态: {}", orderNo, newStatus);
        
        return updatedOrder;
    }
    
    // 生成订单号
    private String generateOrderNo() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = UUID.randomUUID().toString().substring(0, 8);
        return "ORDER" + timestamp + random;
    }
} 